// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.core.property;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dengues.commons.connectivity.IConnectivitySettingsConstants;
import org.dengues.commons.utils.DenguesTextUtil;
import org.dengues.core.DenguesCorePlugin;
import org.dengues.core.ExceptionOperation;
import org.dengues.core.components.ENodeParameterName;
import org.dengues.core.components.IXMLComponent;
import org.dengues.core.components.NodePropertyParameter;
import org.dengues.core.connectivity.IConnectivityProperty;
import org.dengues.core.metadata.MetadataColumn;
import org.dengues.core.metadata.MetadataTable;
import org.dengues.core.process.ICompNode;
import org.dengues.model.database.DatabaseDiagram;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 2007-11-25 qiang.zhang $
 * 
 */
public class NodeParameterUtils {

    private static Map<String, MetadataTable> warehouseTables = new HashMap<String, MetadataTable>();

    private static Map<String, IConnectivityProperty> connectivityProperties = new HashMap<String, IConnectivityProperty>();

    private static Map<String, DatabaseDiagram> warehouseQueries = new HashMap<String, DatabaseDiagram>();

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getDisplayItems".
     * 
     * @param param
     * @return
     */
    public static String[] getDisplayItems(NodePropertyParameter param) {
        return getItems(param, true);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getDisplayItems".
     * 
     * @param param
     * @return
     */
    private static String[] getItems(NodePropertyParameter param, boolean isDisplay) {
        Object[] itemValues;
        if (isDisplay) {
            itemValues = param.getItemNames();
        } else {
            itemValues = param.getItemValues();
        }
        String[] items = new String[0];
        if (itemValues != null) {
            items = new String[itemValues.length];
            for (int i = 0; i < itemValues.length; i++) {
                Object object = itemValues[i];
                if (object instanceof String) {
                    items[i] = (String) object;
                }
            }
        }
        if (items.length == 0) {
            if (param.getName().equals(ENodeParameterName.CONNECTIVITY.getName())) {
                items = initConnectivityProperties();
            } else {
                if (param.isReadOnly()) {
                    items = new String[1];
                    items[0] = IXMLComponent.CUSTOMIZE;
                } else if (param.getName().equals(ENodeParameterName.METADATA.getName())) {
                    if (!param.isReadOnly()) {
                        warehouseTables = DenguesCorePlugin.getDefault().getWarehousePluginService().getWarehouseViewFactory()
                                .getWarehouseTables();
                        String[] names = warehouseTables.keySet().toArray(new String[0]);
                        items = new String[names.length + 1];
                        System.arraycopy(names, 0, items, 0, names.length);
                        items[names.length] = IXMLComponent.CUSTOMIZE;
                    }

                } else if (param.getName().equals(ENodeParameterName.QUERY.getName())) {
                    warehouseQueries = DenguesCorePlugin.getDefault().getWarehousePluginService().getWarehouseViewFactory()
                            .getWarehouseQueries();
                    String[] names = warehouseQueries.keySet().toArray(new String[0]);
                    items = new String[names.length + 1];
                    System.arraycopy(names, 0, items, 0, names.length);
                    items[names.length] = IXMLComponent.CUSTOMIZE;
                }
            }
        }
        return items;
    }

    public static String[] getValueItems(NodePropertyParameter param) {
        return getItems(param, false);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "initConnectivityProperties".
     * 
     * @param items
     * @return
     */
    private static String[] initConnectivityProperties() {
        String[] items = new String[0];
        try {
            IConnectivityProperty[] loadPropertySets = DenguesCorePlugin.getDefault().getDenguesUiService()
                    .getConnectivityManager().getAllConnProperties().toArray(new IConnectivityProperty[0]);
            items = new String[loadPropertySets.length];
            for (int i = 0; i < loadPropertySets.length; i++) {
                IConnectivityProperty connectivityProperty = loadPropertySets[i];
                String split = connectivityProperty.getId().substring(IConnectivitySettingsConstants.PROP_DEFN.length() + 1);
                items[i] = split + IConnectivitySettingsConstants.CONNECTIVITY_DELIMITER + connectivityProperty.getName();
                connectivityProperties.put(items[i], connectivityProperty);
            }
        } catch (Exception ex) {
            ExceptionOperation.operate(ex);
        }
        return items;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getWarehouseTable".
     * 
     * @param text
     * @return
     */
    public static MetadataTable getWarehouseTable(String text) {
        if (warehouseTables.isEmpty()) {
            warehouseTables = DenguesCorePlugin.getDefault().getWarehousePluginService().getWarehouseViewFactory()
                    .getWarehouseTables();
        }
        MetadataTable metadataTable = warehouseTables.get(text);
        if (metadataTable == null) {
            metadataTable = new MetadataTable();
        }
        return metadataTable;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "delimitedParameterValue".
     * 
     * @param value
     * @param needQuote
     * @return
     */
    public static String[] delimitedParameterValue(String value, boolean needQuote) {
        String[] split = value.split(IPropertyController.PARAMETER_SEPERATE);
        String[] ret = new String[split.length];
        for (int i = 0; i < ret.length; i++) {
            String trim = split[i].trim();
            if (needQuote) {
                trim = DenguesTextUtil.addQuotes(trim);
            }
            ret[i] = trim;
        }
        return ret;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getConnectivityProperty".
     * 
     * @param key
     * @return
     */
    public static IConnectivityProperty getConnectivityProperty(String key) {
        return connectivityProperties.get(key);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getConnectivityProperties".
     * 
     * @return
     */
    public static Map<String, IConnectivityProperty> getConnectivityProperties() {
        initConnectivityProperties();
        return connectivityProperties;
    }

    /**
     * Getter for warehouseQueries.
     * 
     * @return the warehouseQueries
     */
    public static Map<String, DatabaseDiagram> getWarehouseQueries() {
        return warehouseQueries;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "changeTablePropertyValue".
     */
    public static List<NodePropertyParameter> changeTablePropertyValue(ICompNode node, boolean init) {
        List<NodePropertyParameter> list = new ArrayList<NodePropertyParameter>();
        for (NodePropertyParameter parameter2 : node.getElementParameters()) {
            EParameterFieldCategory fieldCategory = parameter2.getFieldCategory();
            if (EParameterFieldCategory.TABLE == fieldCategory && parameter2.isBaseSchema()) {
                List<MetadataTable> metadataList = node.getMetadataList();
                if (metadataList.size() > 0) {
                    MetadataTable metadataTable = metadataList.get(0);
                    List<MetadataColumn> columns = metadataTable.getColumns();
                    ArrayList<Map<String, Object>> mappings = (ArrayList<Map<String, Object>>) parameter2.getValue();
                    boolean is = true;
                    if (init) {
                        is = mappings.isEmpty();
                    }
                    if (is) {
                        mappings.clear();
                        String[] itemNames = parameter2.getItemNames();
                        Object[] itemValues = parameter2.getItemValues();
                        for (MetadataColumn metadataColumn : columns) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            for (int j = 0; j < itemNames.length; j++) {
                                String itemName = itemNames[j];
                                if (IXMLComponent.COLUMN_SCHEMA.equals(itemName)) {
                                    map.put(itemName, metadataColumn.getColumnName());
                                } else {
                                    NodePropertyParameter object = (NodePropertyParameter) itemValues[j];
                                    map.put(itemName, object.getValue());
                                }
                            }
                            mappings.add(map);
                            list.add(parameter2);
                        }
                    }
                }
            }
        }
        return list;
    }
}
